package com.example.backend.condition;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

@Slf4j
public class OnOracleAvailableCondition implements Condition {
    private static volatile Boolean oracleAvailableCache = null;

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        if (oracleAvailableCache != null) {
            return oracleAvailableCache;
        }
        String url = context.getEnvironment().getProperty("spring.datasource.oracle.jdbc-url");
        String username = context.getEnvironment().getProperty("spring.datasource.oracle.username");
        String password = context.getEnvironment().getProperty("spring.datasource.oracle.password");
        if (url == null || username == null || password == null) {
            log.warn("Oracle 数据库连接失败: 缺少配置信息");
            oracleAvailableCache = false;
            return false;
        }

        // 显式加载驱动类，防止 ClassNotFound
        try {
            Class.forName("oracle.jdbc.OracleDriver");
        } catch (ClassNotFoundException e) {
            log.warn("Oracle JDBC 驱动未找到，请检查依赖");
            oracleAvailableCache = false;
            return false;
        }
        String sql = "SELECT banner FROM v$version WHERE banner LIKE 'Oracle%'";
        // 尝试资源语句（自动关闭资源）
        try (Connection connection = DriverManager.getConnection(url, username, password);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {

            if (resultSet.next()) {
                String banner = resultSet.getString("banner");
                log.debug("Oracle 数据库连接成功，版本信息: {}", banner);
                oracleAvailableCache = true;
                return true;
            } else {
                log.warn("Oracle 数据库连接成功，但未查询到版本信息");
                oracleAvailableCache = true;
                return true;
            }

        } catch (Exception e) {
            log.warn("Oracle 数据库连接失败: 连接异常: {}", e.getMessage());
            oracleAvailableCache = false;
            return false;
        }
    }
}
